package org.hyjiacan.deadqq.client.window.event;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.JOptionPane;

import org.hyjiacan.deadqq.client.window.RegistWindow;
import org.hyjiacan.deadqq.client.window.WindowManager;
import org.hyjiacan.deadqq.common.entity.User;


public final class Regist implements ActionListener {

	@Override
	public void actionPerformed(ActionEvent e) {
		// TODO Auto-generated method stub
		new Thread() {

			RegistWindow rw = (RegistWindow) WindowManager
					.get(RegistWindow.class.getName());

			@Override
			public void run() {
				User user = rw.getUser();

				try {
					System.out.println("连接服务器");
					Socket s = new Socket("127.0.0.1", 10454);
					ObjectOutputStream oos = new ObjectOutputStream(
							s.getOutputStream());
					System.out.println("发送注册信息");
					oos.writeObject(user);
					oos.flush();
					System.out.println("发送完成，开始接收注册到的账号");

					ObjectInputStream ois = new ObjectInputStream(
							s.getInputStream());
					long n = ois.readLong();
					if (n == -1) {
						System.out.println("注册失败");
						JOptionPane.showMessageDialog(rw,
								"You are not luky.\n Try again please.",
								"Regist failed", JOptionPane.OK_OPTION);
					} else {
						JOptionPane.showMessageDialog(rw,
								"Congratuations.\n You get a account:" + n,
								"Regist success", JOptionPane.OK_OPTION);
						System.out.println("注册到的账号：" + n);
					}
				} catch (UnknownHostException ex) {
					Logger.getLogger(RegistWindow.class.getName()).log(
							Level.SEVERE, null, ex);
				} catch (IOException ex) {
					Logger.getLogger(RegistWindow.class.getName()).log(
							Level.SEVERE, null, ex);
				}
			}
		}.start();
	}
}
